<?php

namespace app\api\controller;

use app\admin\model\Detail;
use app\common\controller\Api;
use app\common\model\ScoreLog;
use fast\Random;
use think\Config;
use app\admin\model\Address;
use app\admin\model\Cart;
use EasyWeChat\Factory;
use app\admin\model\Otherconfig;
use app\admin\model\Song;


/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['miniLogin','login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }
   
    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        if( $avatar ) {
            $user->avatar = $avatar;
        }
        
        $user->save();
        $this->success('suc');
    }
    /**
     * 获取用户信息
     * Summary of getUserInfo
     * @return void
     */
    public function getUserInfo()
    {
      $otherConfig = Otherconfig::find(1);
      $userDetail = $this->auth->getUserinfo();
      $bool =  $userDetail['score'] > $otherConfig['score'];
      $userDetail['luck'] = $bool;
      if( $userDetail['avatar']) {
        $userDetail['avatar'] = $this->request->domain().$userDetail['avatar'];
      }
     
      $this->success('suc', $userDetail);
    }
    /**
     * 文件上传
     * Summary of upload
     * @return void
     */
    public function upload()
    {
        $file = $this->request->file('file');
        if (!$file) {
            $this->error('请选择要上传的文件');
        }
        $upload = new \app\common\library\Upload($file);
        // 检查是否为图片文件
        $fileInfo = $file->getInfo();
        $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];    
        $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];     
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        
        if (!in_array($fileInfo['type'], $allowedTypes) && !in_array($suffix, $allowedExts)) {
            $this->error('只允许上传图片文件(jpg、png、gif、bmp、webp)');   
        }
        // 执行上传
        $attachment = $upload->upload();
        $this->success('上传成功', [
            'url' => $attachment->url,
            'filename' => $attachment->filename,
        ]);
    }
    /**
     * 我的地址
     * Summary of address
     * @return void
     */
    public function address()
    {
        $list = Address::where(['user_id' => $this->auth->id,'status' => 1])->select();
        $this->success($list);
    }
    /**
     * 添加或修改
     * Summary of editAddress
     * @return void
     */
    public function editAddress() {
        $id = $this->request->post('id',0);
       
        $name = $this->request->post('name');
        $address = $this->request->post('detail');
        $area = $this->request->post('area');
        $phone = $this->request->post('phone');
        if(!preg_match('/^1[3-9]\d{9}$/', $phone)){
            $this->error('手机号码有误');
        }
        $default = $this->request->post('default',0);
        if(empty($name) || empty($address)) $this->error('参数有误');
        if(empty($id)) {
            $detail = new Address();
        } else {
            $detail = Address::find($id);
        }
      
        if(empty($detail)) $this->error('非法请求');
        
        $detail->name = $name;
        $detail->phone = $phone;
        $detail->area = $area;
        $detail->status = 1;
        $detail->detail = $address;
        $detail->user_id = $this->auth->id;
        if( $default)  {//如果是默认
            Address::where(['user_id' => $this->auth->id])->update(['default' => 0]);
        }
        $detail->default =  $default;
        $result = $detail->save();
        if($result) $this->success('操作成功');
        $this->error('操作失败请求');
    }
    /**
     * 删除地址：
     * Summary of delAddress
     * @param mixed $id
     * @return void
     */
    public function delAddress($id = null) {
        if(empty($id)) $this->error('非法请求');
        $result = Address::where(['id' => $id])->update(['status' => 0,'default' => 0]);
        if($result) $this->success('删除成功');
        $this->error('删除失败');
    }
    /**
     * 设置为默认地址
     * Summary of setDefault
     * @param mixed $id
     * @return void
     */
    public function setDefault($id = null)
    {
        if(empty($id)) $this->error('非法请求');
        $result = Address::find($id);
        if($result['default'] == 1)  $this->success('修改成功');
        Address::where(['user_id' => $this->auth->id])->update(['default' => 0]);
        Address::where(['id' => $id])->update(['default' => 1]);
        $this->success('修改成功');
        
        
    }
    /**
     * 我的推广、积分
     * Summary of tuig
     * @param mixed $type
     * @param mixed $page
     * @return void
     */
    public function tuig($type = 0,$page = 1,$time = '')
    {
      //0=自购积分,1=自购水滴,2=推广水滴,3=抽奖消耗积分,4=提现消耗水滴,5=抽奖获得积分,6=抽奖获得水滴
        $where = [];
        if($type == 0) {//积分,全部找出来
            $where['status'] = 0;
            $where['user_id'] = 9;
        } else if($type == 1) {//水滴，全部找出来
            $where['status'] = 1;
            $where['user_id'] = 9;
        } else{//推广水滴，只找推广的
            $where['status'] = 1;
            $where['pid'] = 9;
            $where['type'] = 2;
        }
        if($time) {//如果有时间
            $date = date('Y-m-d',strtotime($time));
           
            $startTime = strtotime(date($date.'00:00:00'));
            $endTime = strtotime(date($date.'23:59:59'));
            $where['createtime'] = ['between',[$startTime, $endTime]];
        }
        $list = ScoreLog::where( $where)->order('id desc')->paginate(20,false,['page' => $page]);
        $list->each(function($item){
            $userDetail =  \app\admin\model\User::find($item['user_id']);
            $item['username'] = $userDetail['username'];
            $item['create_time'] = date('Y-m-d H:i:s',$item['createtime']);
        });
        
        $this->success($list);
    }
    /**
     * 
     * 添加到购物车
     * @return void
     */
    public function addCart()
    {
        $productId = $this->request->get('productId',0);
        if(empty($productId) ) $this->error('参数有误');
        $list = Detail::find( $productId);
        if(empty($list)) $this->error('产品信息有误');

        if(!$list['status']) $this->error('产品已下架');

        $num = $this->request->get('num',1);

        $cart = new Cart();

        $cart->user_id = $this->auth->id;

        $cart->detail_id = $productId;

        $cart->num = $num;

        $cart->money = $list['money'] * $num;

        $cart->create_time = time();

        $result = $cart->save();
       
        if($result) $this->success('suc');
        $this->error('fail');
    }
    /**
     * 购物车删除
     * Summary of delCart
     * @param mixed $ids
     * @return void
     */
    public function delCart($ids = null)
    {
       if(!$ids) $this->error('fail');
       if(is_string($ids)) {
          $ids = explode(',',$ids);
       }
       $result = Cart::where('id', 'in', $ids)->delete();
     
       if($result) $this->success('suc');

       $this->error('fail');
    }
    /**我的购物车
     * Summary of carList
     * @return void
     */
    public function carList()
    {
        $user_id = $this->auth->id;
        
        $list = Cart::with(['product'])
            ->where('user_id', $user_id)
            ->order('id', 'desc')
            ->select();
        $list = Collection($list)->toArray();
        if(empty($list)) $this->success('suc');
        foreach($list as $key =>$value) {
             $list[$key]['product']['images'] = dealImages($this->request->domain(),$value['product']['images']);
        }
        $total = 0;
        foreach ($list as $key => $value) {
            $total += $value['money'];
        }    
      
        $this->success('获取成功', ['data' => $list,'total' => $total]);
    }
    public function miniLogin()
    { 
        error_reporting(error_reporting() & ~E_DEPRECATED);
            $postData = file_get_contents('php://input');
            if(!$postData)  $this->error(__('数据格式有问题'));
            $postData = json_decode($postData,true);
            if(!$postData)  $this->error(__('转换失败，提交数据有问题'));
      
            $code = $postData['code'];
            $encryptedData = $postData['encryptedData'] ;
            $iv = $postData['iv'];
            $inviteCode = isset($postData['inviteCode'])? $postData['inviteCode']:'';
          
            if (!$code || !$encryptedData || !$iv ) {
                throw new \Exception('参数有误');
            }
            $siteConfig = Otherconfig::find(1);
            $config = [
                'app_id' => $siteConfig['app_id'],
                'secret' =>  $siteConfig['secret']
            ];
           

            
            $app = Factory::miniProgram($config);
            $result = $app->auth->session($code);
            $decryptedData = $app->encryptor->decryptData( $result['session_key'], $iv, $encryptedData);
            if (!$decryptedData) {
                return $this->error('用户信息解密失败');
            }
            $mobile = isset($decryptedData['phoneNumber']) ? $decryptedData['phoneNumber'] : '';
            
            if (!$mobile) {
                return $this->error('未能获取到用户手机号',$decryptedData);
            }
            $pid = $agentId =0;
            if($inviteCode) {#如果有邀请码；
                $has = \app\common\model\User::where(['invite_code' => $inviteCode])->find();
                $pid = $has['id'];
            }
            $user = \app\common\model\User::getByMobile($mobile);
            
            if ($user) {
                if ($user->status != 'normal') {
                    $this->error(__('Account is locked'));
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id, $result['openid']);
            } else {
                $ret = $this->auth->register($mobile, Random::alpha(), '', $mobile, ['agent_id' => $agentId,'invite_code' => Random::alpha(),'open_id' =>  $result['openid'],'pid' => $pid]);
            }
            if ($ret) {
                //Sms::flush($mobile, 'mobilelogin');
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            } 
    }
    
    public function deliveryLogin()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $userId = $this->request->post('userId');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $user = Song::get(['account' => $account]);
        if (!$user) {
            $this->error('账号不存在');
        }
        if ($user->status == 0) {
            $this->error('账号异常');
        }
        if ($user->password != $this->auth->getEncryptPassword($password, $user->salt)) {
            $this->error('密码错误');
            return false;
        }
        $user->token = random::uuid();
        $user->user_id =  $userId;
        $result = $user->save();
        if(!$result) $this->error('登录失败');
        $this->success('suc',['id' => $user->id,'token'=> $user->token]); 
    } 


}
